<template>
  <div class="form-setting-panel form-connector-setting" :key="formConnectorSettingKey">
    
    <!-- start 标题 -->
    <form-title-setting
      :field="field"
      :setting="setting"
      :disabled="false"
      :show-question-icon="false"
      @input="updateForDom"
      :form-title-max-length="20"
    ></form-title-setting>
    <!-- end 标题 -->
    
    <!-- start 描述信息 -->
    <form-describe-setting
      :field="field"
      :mode="mode"
      @input="updateForDom"
      :info="$t('common.connector.connectorFieldInfo')"
    ></form-describe-setting>
    <!-- end 描述信息 -->

    <!-- start 数据来源 -->
    <FormConnectorDataRuleSetting 
      :template-name="templateName" 
      :from-fields="fromFieldList" 
      :from-app-data="fromAppData"
      :field="field"
      ref="formConnectorDataRuleSetting"
      :is-created="isCreated"
      @updateForKey="update"
      @input="handleUpdateDataRuleSetting"/>
    <!-- end 数据来源 -->
    
    <!-- start 数据查询 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{ $t('common.connector.scoped') }}</h4>
      <div class="form-item-box">
        
        <!-- start 设置数据查询条件 -->
        <!-- <FormConnectorRuleSetting
          v-if="bizTypeId"
          :configData="configData"
          @ruleChange="updateRuleSetting"
          type="select"
          :fromApp="fromApp"
          :toApp="toApp"
        /> -->
        <!-- end 设置数据查询条件 -->
        
        <div class="form-connector-setting-select-auto">
          <span>{{ $t('common.connector.autoMatch.text1') }}
            <el-tooltip placement="top" popper-class="form-msg-setting-tooltip">
              <div slot="content">
                <div class="tooltip">{{ $t('common.connector.autoMatch.text2') }}<br>{{ $t('common.connector.autoMatch.text3') }}</div>
              </div>
              <i class="iconfont icon-question"></i>
            </el-tooltip>
          </span>
          <el-switch :value="isMatch" @change="updateSettingIsMatch" :true-label="1" :false-label="0"></el-switch>
        </div>

        <!-- start 选项显示模式 -->
        <form-displaymode-setting :field="field" @input="update" :isMulti="false" :showTooltip="false" :options="connectorDisplayModes" :validate="handleValidateMode"></form-displaymode-setting>
        <!-- end 选项显示模式 -->
        
      </div>
    </div>
    <!-- end 数据来源 -->
    
    <!-- start 校验 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{ $t('common.base.check') }}</h4>
      <div class="form-item-box">
        <!-- 必填 -->
        <form-required-setting :field="field" @input="update"></form-required-setting>
      </div>
    </div>
    <!-- end 校验 -->
    
    <!-- start 字段权限 -->
    <div class="form-setting-group form-setting-item form-setting-role-item" v-if="!isServiceProviderFlag">
      <h4 class="form-item-title">{{ $t('common.base.fieldPermissions') }}</h4>
      <div class="form-item-box">
        <!-- 可见性 -->
        <form-visible-setting :field="field" @input="update"></form-visible-setting>
        <!-- 暂不支持高级搜索 -->
        <!-- <form-search-setting :field="field" @input="update"></form-search-setting> -->
      </div>
    </div>
    <!-- end 字段权限 -->
  
  </div>
</template>

<script>
/* components */
import SearchTree from './SearchTree/SearchTree.vue';
import FormConnectorRuleSetting from './FormConnectorRuleSetting';
import { ConnectorModuleConnectorDialogDetailColumn } from '@src/modules/connector/components';
import FormConnectorDataRuleSetting from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting'
/* mixin */
import SettingMixin from '@src/component/form/mixin/setting';
import FormSubFormMixin from '@src/component/form/mixin/form.subForm';

/** api */
import { getFormModuleList, getFormOptions } from '@src/modules/connector/api';
/* model */
import { ConnectorBizTypeEnum, ConnectorOptionsActionEnum} from '@src/modules/connector/model';
/* util */
import {
  formFields2ConnectorFromFields,
  connectorRuleFormToConnectorOptionsFieldOption,
  sortConnectorToFieldsByShowFieldNameList,
  connectServerValueToComponentValueForEditWithTaskToPaas, 
  connectorToFields2FormFields,
  getSortConnectorToFieldsByShowFieldNameList
} from '@src/modules/connector/util';
import { message } from "@src/util/message";
import { uuid } from 'pub-bbx-utils'
import { cloneDeep, isString } from 'lodash'

const modeBizTypeMap = {
  event: ConnectorBizTypeEnum.Event,
  customer: ConnectorBizTypeEnum.Customer,
  product: ConnectorBizTypeEnum.Product,
  projectType: ConnectorBizTypeEnum.Project,
}

export default {
  name: 'form-connector-setting',
  mixins: [SettingMixin, FormSubFormMixin],
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    fields: {
      type: Array,
      default: () => []
    },
    mode: {
      type: String,
      default: ''
    },
    setting: {
      type: Object,
      default: () => ({})
    },
    templateId: {
      type: String,
      default: ''
    },
    templateName: {
      type: String,
      default: ''
    }
  },
  components: {
    SearchTree,
    FormConnectorRuleSetting,
    ConnectorModuleConnectorDialogDetailColumn,
    FormConnectorDataRuleSetting
  },
  data() {
    return {
      // 数据来源
      appDataList:[],
      // 展示字段的数据
      selectedColumns: [],
      componentTableColumns: [],
      options:[],
      initColumn: false,
      additionalId: 0,
      configData: {},
      fromApp: {
        name: this.templateName
      },
      toApp: {},
      bizTypeId: '',
      uniqueId: '', // bizType + '@' + bizTypeId
      treeDefaultProps: {
        children: 'children',
        label: 'name',
        key: 'bizTypeId'
      },
      computedFieldList: [],
      selectedColumnsKey: uuid(),
      formConnectorSettingKey: uuid(),
    };
  },
  computed: {
    connectorDisplayModes() {
      return [
        {
          label: 1,
          value: this.$t('common.connector.mode.option')
        },
        {
          label: 2,
          value: this.$t('common.connector.mode.list')
        },
      ]
    }, 
    connector() {
      return this.field?.setting?.connector
    },
    showFieldList(){
      return this.connector?.toFieldList?.map(field => {
        let newItem = field;
        newItem.show = false;
        (this.connector?.showFieldNameList || []).forEach(item=>{
          if(field.enName == item){
            newItem.show = true
          }
        })
        return newItem
      })
    },
    // 是否多选
    isMulti() {
      return Boolean(this.field?.setting?.isMulti)
    },
    // 是否自动带入
    isMatch() {
      return Boolean(this.field?.setting?.isMatch)
    },
    fromFieldList() {
      return formFields2ConnectorFromFields(this.fields)
    },
    fromAppData() {
      const { fromBizType, fromBizTypeId } = this.field.setting || {}
      return {
        fromBizType,
        fromBizTypeId
      }
    },
    originSettingData() {
      const originData = this.field.setting?.originData
      if(isString(originData)) {
        return JSON.parse(originData)
      }
      return null
    },
    isCreated() {
      return Boolean(this.connector?.additionalId) || false
    }
  },
  watch:{
    field: {
      async handler(){
        console.log('FormConnectorSetting watch field', this.field)
        try {
          
          if(!this.appDataList.length){
            await this.getAppList()
          }
          
          this.init()
          
          const connector = this.field?.setting?.connector
          if(connector) {
            
            let { additionalId, toBizTypeId, showFieldNameList, toFieldList = [], hasSelectData, actionList = [] } = connector

            toFieldList = actionList.find(item=> item.action === ConnectorOptionsActionEnum.Select)?.toRequestFieldList || [];
            
            this.computedFieldList = toFieldList
            
            if(additionalId || hasSelectData) {
              
              this.initColumn = true
              this.additionalId = additionalId
              
              const sortedToFieldList = sortConnectorToFieldsByShowFieldNameList(toFieldList, showFieldNameList || [])
              const editOptions = {
                ...connector,
                toFieldList: sortedToFieldList
              }
              
              this.computedFieldList = sortedToFieldList.map(item => {
                
                const showFieldNameListValue = showFieldNameList || []
                
                const fieldName = item.enName || ''
                
                const newItem = {
                  ...item,
                  show: showFieldNameListValue.includes(fieldName)
                }
                
                return newItem
                
              });
              
              const selectedColumns = getSortConnectorToFieldsByShowFieldNameList(sortedToFieldList, showFieldNameList || [])
              this.selectedColumns = connectorToFields2FormFields(selectedColumns);
              
              this.options = connectorToFields2FormFields(selectedColumns)
              
              const detailValue = connectServerValueToComponentValueForEditWithTaskToPaas(editOptions)
              this.bizTypeId = toBizTypeId
              this.configData = detailValue
              this.configData.toFieldList = toFieldList
              this.configData.fromFieldList = formFields2ConnectorFromFields(this.fields)
              this.toApp = detailValue.paasApp
              this.$refs.formConnectorDataRuleSetting.setDefaultData(cloneDeep(this.convertConnectDataToFormData(connector)))
            }
          }
        } catch (error) {
          console.log('error: ' + error)
        }
      },
      immediate: true
    },
  },
  mounted() {
    this.addConnectorFromData()
  },
  methods: {
    convertConnectDataToFormData(connector = {}) {
      const { dataSource = [], actionList = [], showFieldNameList = [], toBizTypeId = '', toBizType = '', toBizTypeName = '', toBizTypeLogo = ''} = connector
      return {
        formConnectorDataRuleSettingFilterConfig:  {
          ...this.configData,
          fromApp: {
            name: this.templateName
          }
        },
        dataSource,
        interface: actionList?.[0] || {},
        selectShowFieldNameList: showFieldNameList,
        selectFormValue: { 
          bizTypeId:toBizTypeId, bizType: toBizType, label: toBizTypeName, icon: toBizTypeLogo
        }
      }
    },

    init() {
      
      console.log('FormConnectorSetting init')
      
      this.additionalId = 0
      this.initColumn = false
      this.computedFieldList = []
      this.selectedColumns = []
      this.options = []
      this.bizTypeId = ''
      this.configData = {}
    },
    removeField(index) {
      console.log('FormConnectorSetting removeField')
      this.selectedColumns.splice(index, 1)
    },
    updateRuleSetting(val) {
      
      console.log('FormConnectorSetting updateRuleSetting')
      
      if (!val) return;
      
      this.configData = val
      
      // 更新 selectFieldOptionsList
      const selectFieldOptionsList = (val.selectRuleForms || []).map(item => connectorRuleFormToConnectorOptionsFieldOption(item,true))
      
      this.$set(this.field.setting.connector, 'selectFieldOptionsList', selectFieldOptionsList)
      
    },
    openSelectColumnDialog(){
      
      console.log('FormConnectorSetting openSelectColumnDialog')
      
      if (!this.bizTypeId) {
        message.error(this.$t('common.connector.validate_rule.selectApp'))
        return
      }
      
      this.$refs.selectColumnRef?.openSelectColumnDialog()
    },
    onConnectorShowFieldNameListSaveHandler(value) {
      this.componentTableColumns = value
    },
    onConnectorShowFieldNameListInputHandler(value){
      
      console.log('FormConnectorSetting onConnectorShowFieldNameListInputHandler')
      
      this.$nextTick(() => {
        
        const tableColumns = this.componentTableColumns
        
        this.options = tableColumns
        this.selectedColumns = tableColumns.filter(item=> item.show)
        this.$refs.selectColumnRef?.setTableColumns(tableColumns)
        
        // 选择列这里重新渲染一遍
        this.selectedColumnsKey = uuid()
        
        this.$set(this.field.setting.connector, 'showFieldNameList', value)
        
      })
      
    },
    /* 选择联动表单 */
    handleTreeSelect(selected) {
      console.log('FormConnectorSetting handleTreeSelect')
      // 选择相同联动表单
      // console.log('handleTreeSelect', selected, this.bizTypeId)
      if(this.additionalId) return message.warning(this.$t('common.connector.disableEditApp'))
      if (selected.bizTypeId == this.bizTypeId) return
      this.toApp = selected
      // 重置关联字段、条件
      this.configData = {}
      this.options = []
      this.selectedColumns = []
      this.bizTypeId = selected.bizTypeId
      this.uniqueId = selected.uniqueId
      // "toBizType":"xxxx",
      // "toBizTypeId":"1111",
      // "toBizTypeName":"xxxx",
      const toBiz = {
        toBizType: selected.bizType,
        toBizTypeId: selected.bizTypeId,
        toBizTypeName: selected.name
      }
      this.$set(this.field.setting, 'connector', {...this.field.setting.connector, ...toBiz})
      // 根据所选的应用获取toFieldList字段
      const params = {}
      params.bizType = selected.bizType
      params.bizTypeId = this.bizTypeId
      getFormOptions(params).then((res) => {
        
        
        const result = res?.data || []
        
        if (res.status === 0) {
          this.initColumn = true
          
          this.computedFieldList = cloneDeep(result).map(item => {
            item.show = false
            return item
          })
          
          this.configData.toFieldList = result
          
          this.configData.fromFieldList = formFields2ConnectorFromFields(this.fields)
          this.$set(this.field.setting, 'connector', {...this.field.setting.connector, ...this.configData, 'hasSelectData': true })
        }
      });
    },
    // 获取应用数据
    async getAppList(){
      console.log('FormConnectorSetting getAppList')
      try {
        const params = {}
        params.fromBizTypeId = this.templateId
        const { status, data } = await getFormModuleList(params)
        if (status === 0) {
          this.appDataList = data || [];
          this.appDataList.forEach(module => {
            module.children.forEach(item => {
              item.uniqueId = `${item.bizType}@${item.bizTypeId}`
            })
          })
        }
      } catch (error) {
        console.warn('FormConnectorSetting getAppList error', error)
      }
    },
    updateForDom(event){
      console.log('FormConnectorSetting updateForDom')
      let el = event.target;
      let prop = el.dataset.prop;
      let value = el.value;

      this.update(value, prop);
    },
    update(value, prop, isSetting = false) {
      console.log('FormConnectorSetting update')
      this.$emit('input', {value, prop, isSetting});
    },
    updateSettingIsMulti(value) {
      
      console.log('FormConnectorSetting updateSettingIsMulti')
      
      const newValue = Boolean(value)
      
      this.$set(this.field.setting, 'isMulti', newValue)
      
      const isSetting = true
      
      this.update(newValue, 'isMulti', isSetting)
      
    },
    updateSettingIsMatch(value) {
      
      console.log('FormConnectorSetting updateSettingIsMatch')
      
      const newValue = Number(value)
      
      this.$set(this.field.setting, 'isMatch', newValue)
      
      const isSetting = true
      
      this.update(newValue, 'isMatch', isSetting)
      
    },
    rerender() {
      this.formConnectorSettingKey = uuid()
    },
    /** 
     * @description 添加连接器 from 数据
    */
    addConnectorFromData() {
      
      const originFromBizType = this.connector?.fromBizType || ''
      const originFromBizTypeId = this.connector?.fromBizTypeId || ''
      
      if (originFromBizType || originFromBizTypeId) {
        return
      }
      
      const fromBizType = modeBizTypeMap[this.mode] || ''
      const fromBizTypeId = this.templateId || ''
      
      if (!fromBizType || !fromBizTypeId) {
        console.warn('FormConnectorSetting addConnectorFromData waring: fromBizType or fromBizTypeId is empty')
        return
      }
      
      const connector = {
        ...this.connector,
        fromBizType,
        fromBizTypeId
      }
      
      const isSetting = true
      
      this.update(connector, 'connector', isSetting);
    },
    /**
     * Description 相关数据来源的规则设置
     * @param {any} v
     * @returns {any}
     */
    handleUpdateDataRuleSetting(v) {

      const { dataSource, formConnectorDataRuleSettingFilterConfig = {}, selectFormValue = {}, selectShowFieldNameList: showFieldNameList = [] } = v
      const { selectRuleForms = [], fromFieldList, toFieldList, actionList: defaultActionList = [], conditionalLimit } = formConnectorDataRuleSettingFilterConfig || {}
      // 重组更新 selectFieldOptionsList
      const selectFieldOptionsList = selectRuleForms && (selectRuleForms || []).map(item => connectorRuleFormToConnectorOptionsFieldOption(item, true))
      const { bizType: toBizType, bizTypeId: toBizTypeId, label: toBizTypeName, icon: toBizTypeLogo } = selectFormValue || {}

      // 删除actionList中不需要的key
      const actionList = defaultActionList.map(action=> {
        const copyAction = cloneDeep(action)
        return copyAction
      })

      // 重新组合的参数
      const settingConnectorParams = {
        selectFieldOptionsList,
        toBizType,
        toBizTypeId,
        toBizTypeName,
        toBizTypeLogo,
        showFieldNameList,
        actionList,
        toFieldList,
        fromFieldList,
        dataSource,
        conditionalLimit,
      }

      const updateConnectData = {...this.field.setting.connector, ...settingConnectorParams };

      if(!this.connector) {
        updateConnectData.hasSelectData = true;
      }

      this.$set(this.field.setting, 'connector', updateConnectData)
      // this.update(JSON.stringify(v), 'originData', true)
    },
    handleValidateMode(value) {
      // 选项模式不支持自定义字段
      if (this.field?.setting?.subFormFieldList?.length && value != 2) {
        return this.$t('common.connector.mode.tip');
      }
    },
  }
}
</script>
<style lang="scss" scoped>
@import '@src/component/form/components/FormSubForm/FormSubForm.scss';
.form-item-box{
  margin-top: 10px;
  .form-connector-setting-select-auto {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    i {
      margin-left: 8px;
    }
  }
}
.el-cascader{
  width: 100%;
  ::v-deep .el-input {
    line-height: 8px !important; 
  }
}

</style>
<style lang="scss">
.form-setting-item-select {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-checkbox {
    margin-top: 0!important;
  }
}

.form-setting-item-data-source {
  display: flex;
  min-height: 32px;
  padding: 3px 10px;
  line-height: 24px;
  border: 1px solid #e0e1e2;
  border-radius: 4px;
  margin-bottom: 0;
  outline: none;
  color: #333 !important;
}

.connectorSettingSelectColumn {
  display: none!important;;
}

.selectShowColumn {
  .el-input.is-disabled {
    .el-input__inner, .el-input__icon {
      cursor: pointer!important;
    } 
  }
  .el-input.is-disabled .el-input__inner{
    background-color: #fff !important;
    border-color: #e0e1e2 !important;
  }
}

.connector-component-rule-setting {
  width: 840px !important;
  z-index: 99999!important;
}

.form-connector-setting-select-btn {
  width: 100%;
  height: 32px;
  background: $color-primary-light-1!important;
  border-radius: 3px;
  border: 1px solid $color-primary-light-2;
  color: $color-primary!important;
  margin-bottom: 12px;
  &:hover {
    color: #fff!important;
  }
}
.config-panel-setting-detail{
  border-radius: 2px;
  border: 1px solid #E8E8E8;
  margin-top: 4px;
  margin-bottom: 16px;
  .setting-title{
    height: 28px;
    background: #FAFAFA;
    line-height: 28px;
    font-size: 14px;
    color: #262626;
    padding-left: 12px;
  }
  .setting-content{
    padding: 12px;
  }
  .rule-text{
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #595959;
    line-height: 24px;
    span{
      // display: inline-block;
      // width: 38%;
    }
    .operator-text{
      // width: 20%;
    }
    .and-text,.operator-text{
      color:#8c8c8c;
    }
  }
}
.config-panel-setting {
  .el-button--primary.is-plain{
    width: 100%;
    color: $color-primary-light-6!important;
    background-color: $color-primary-light-1 !important;
    &:hover{
      background-color: $color-primary-light-6!important;
      color: #fff!important;
    }
  }
}
.form-connector-setting {
  .form-setting-group-small {
    margin-bottom: 12px;
  }
}

.selectShowColumn {
  .el-select-dropdown {
    display: none;
  }
}
</style>
